<script setup lang="ts">
import { ref } from 'vue'
import { onLoad, onReachBottom } from '@dcloudio/uni-app'
import { sellerPage, buyerPage } from '@/api/order'
import type { Order, OrderReq } from '@/api/order/type'
import type { BaseResponse } from '@/api/base'
import { toast } from '@/utils/common'

const orderList = ref<Order[]>([])
const queryParams = ref<OrderReq>({
  pageNum: 1,
  pageSize: 10
})
const currentTab = ref<number>(0)
const moreStatus = ref<boolean>(true)

import buyer from './buyer.vue'
import seller from './seller.vue'

const list = ref([
  {
    name: '我卖出的',
    value: 0
  },
  {
    name: '我购买的',
    value: 1
  }
])

const handlePageInfo = (res: BaseResponse) => {
  if (queryParams.value.pageNum == 1 && res.data.records.length < queryParams.value.pageSize) {
    moreStatus.value = false
    orderList.value = orderList.value.concat(res.data.records)
    queryParams.value.total = res.data.total
    return
  }
  if (!res.data || res.data.records.length == 0 || res.data.total < orderList.value.length) {
    moreStatus.value = false
    return
  }
  orderList.value = orderList.value.concat(res.data.records)
  queryParams.value.pageNum++
}

const loadSellerOrderList = async () => {
  try {
    const res: BaseResponse = await sellerPage(queryParams.value)
    handlePageInfo(res)
  } catch (error) {
    moreStatus.value = false
    toast(error.tips)
  }
}
const loadBuyerOrderList = async () => {
  try {
    const res: BaseResponse = await buyerPage(queryParams.value)
    handlePageInfo(res)
  } catch (error) {
    moreStatus.value = false
    toast(error.tips)
  }
}

onLoad(async () => {
  loadSellerOrderList()
})
onReachBottom(() => {
  // 如果依然还有数据，就触发
  if (moreStatus.value == true) {
    setTimeout(() => {
      loadTabData()
    }, 500)
  }
})

const loadTabData = () => {
  if (currentTab.value === 0) {
    loadSellerOrderList()
  } else {
    loadBuyerOrderList()
  }
}

const switchTab = (item: any) => {
  currentTab.value = item.value
  reset()
  loadTabData()
}

const reset = () => {
  moreStatus.value = true
  orderList.value = []
  queryParams.value = {
    pageNum: 1,
    pageSize: 10
  }
}
uni.$on('backRefresh', () => {
  reset()
  loadTabData()
})
const refresh = () => {
  reset()
  loadTabData()
}
</script>

<template>
  <view class="order">
    <uv-sticky bgColor="#fff">
      <uv-tabs :current="currentTab" :list="list" @click="switchTab"></uv-tabs>
    </uv-sticky>
    <seller :showSeller="currentTab === 0" :orderList="orderList" @refresh="refresh"></seller>
    <buyer :showBuyer="currentTab === 1" :orderList="orderList" @refresh="refresh"></buyer>
  </view>
</template>

<style lang="scss" scoped></style>